package com.icss.ah.base.action;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;

import net.sf.json.JSONObject;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.icss.ah.base.bean.Json;
import com.icss.ah.base.util.VerifyCodeUtils;

/**
 * 验证码生成
 * @author csadchen
 * @date 2016-09-18
 */
@Controller
@Scope("prototype")
public class VerifyCodeAction extends BaseAction{
	
	int w = 200, h = 100;
	// json串
	private Json jsonText;
	/**
	 * 刷新验证码
	 */
	public void refresh(){
		try{
			//页面传入高度宽度
			String widthP = getRequest().getParameter("widthP");
			String heightP = getRequest().getParameter("heightP");
			w = widthP==null ? w : Integer.parseInt(widthP);
			h = heightP==null ? h : Integer.parseInt(heightP);
			//生成验证码
			String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
			//画图
			BufferedImage image = VerifyCodeUtils.outputImage(w, h, verifyCode);
			//将验证码保存到session
			getRequest().getSession().setAttribute("verifyCode", verifyCode);
			//返回到页面
			ImageIO.write(image, "jpg", getResponse().getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 查询验证码的值
	 * @return
	 */
	public void findPinNum() {
		request = this.getRequest();
		jsonText = new Json();
		try {
			//从session中获取验证码
			String verifyCode = getRequest().getSession().getAttribute("verifyCode") == null ? "" : getRequest().getSession().getAttribute("verifyCode").toString();
			jsonText.setSuccess(true);
			jsonText.setObj(verifyCode);
		} catch (Exception e) {
			e.printStackTrace();
			jsonText.setSuccess(false);
			jsonText.setMsg(e.getMessage());
		}
		str2Resp(JSONObject.fromObject(jsonText).toString());
		
	}
	
	
}
